package com.itheima.HomeWork_day14;

import javax.swing.plaf.nimbus.AbstractRegionPainter;

/*
同步代码块\同步方法\同步静态方法锁对象练习
 */
public class SynchTest01 {
    public static void main(String[] args) {

        //创建参数对象
        MyRun my=new MyRun();
        Thread t1=new Thread(my);
        Thread t2=new Thread(my);


        t1.setName("窗口1");
        t2.setName("窗口2");

        t2.start();
        t1.start();

    }
}


class MyRun implements Runnable {

    private static int ticket = 100;
    @Override
    public void run() {
        while (true) {

            if ("窗口1".equals(Thread.currentThread().getName())) {
                //执行同步代码方法
                boolean result = getTicket();
                if (result) {
                    break;
                }
            }

            if ("窗口2".equals(Thread.currentThread().getName())){
                //执行同步代码块
                //使用同步锁,使用相同的锁对象
                synchronized (MyRun.class) {
                    //如果票数为0的时候,就结束循环
                    if (ticket == 0) {
                        System.out.println("票已经售完!");
                        break;
                    } else {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //票数减1
                        ticket--;
                        System.out.println(Thread.currentThread().getName() +
                                "正在售票中ing...,还剩" + ticket + "张");
                    }
                }

            }
        }
    }

    //使用同步方法
    private static synchronized boolean getTicket() {

        //判断票数
        if (ticket == 0) {
            System.out.println("票已经售完！");
            return true;
        } else {
      //睡眠
          try {
              Thread.sleep(10);
            } catch (InterruptedException e) {
                   e.printStackTrace();
            }
          //如果票数为0的时候,就结束循环
                        //票数减1
                        ticket--;
                        System.out.println(Thread.currentThread().getName() +
                                "正在售票中ing...,还剩" + ticket + "张");
            return false;
        }
    }
}